package com.fishery.processing.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fishery.entity.GlobalException;
import com.fishery.entity.StatusCode;
import com.fishery.processing.async.BatchAsync;
import com.fishery.processing.entity.ProductBatch;
import com.fishery.processing.entity.vo.BeforeMessageVo;
import com.fishery.processing.entity.vo.ProductBatchVo;
import com.fishery.processing.entity.vo.RootMessageVo;
import com.fishery.processing.mapper.ProductBatchMapper;
import com.fishery.processing.service.ProductBatchService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fishery.processing.util.ConvertUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author run
 * @since 2021-03-12
 */
@Service
public class ProductBatchServiceImpl extends ServiceImpl<ProductBatchMapper, ProductBatch> implements ProductBatchService {

    @Autowired
    private ConvertUtil convertUtil;

    @Autowired
    private ProductBatchMapper batchMapper;

    @Autowired
    private BatchAsync batchAsync;

    @Override
    public IPage<ProductBatchVo> getBatchOfFactory(String factoryId, Integer page, Integer size) {
        IPage<ProductBatch> batchIPage = new Page<>(page, size);
        QueryWrapper<ProductBatch> wrapper = new QueryWrapper<>();
        wrapper.eq("processing_factory_id", factoryId);

        return convertUtil.convert(batchMapper.selectPage(batchIPage, wrapper), ProductBatchVo.class);
    }

    @Override
    public ProductBatchVo getBatchById(String batchId) {
        return convertUtil.convert(batchMapper.selectById(batchId), ProductBatchVo.class);
    }

    @Override
    public boolean setInventoryOfBatch(String batchId, Double weight) {
        return batchMapper.setInventoryOfBatch(batchId, weight) > 0;
    }

    @Override
    public RootMessageVo getMessageOfBatch(String batchId) {
        ProductBatch batch = batchMapper.selectById(batchId);
        RootMessageVo messageVo = new RootMessageVo();
        CountDownLatch count = new CountDownLatch(2);
        batchAsync.setFactoryMessage(messageVo, batch.getProcessingFactoryId(), count);
        batchAsync.setJobMessage(messageVo, batch.getJobId(), count);

        try {
            count.await(5, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            throw new GlobalException(StatusCode.ERROR, "获取超时");
        }

        return messageVo;
    }

    @Override
    public BeforeMessageVo getBeforeMessageOfBatch(String batchId) {
        return batchMapper.getBeforeMessageOfBatch(batchId);
    }
}
